package sixkey.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import sixkey.annotation.LogAnnotation;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

import static org.springframework.web.context.request.RequestContextHolder.resetRequestAttributes;

/**
 * ClassName:LogAspect
 * Package:sixkey.aop
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/6/22 - 10:40
 * @Version:v1.0
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    //切点
    @Pointcut("@annotation(sixkey.annotation.LogAnnotation)")
    public void pointcut(){};

    //环绕通知
    @Around("pointcut()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        //记录方法执行时间
        long begin = System.currentTimeMillis();
        //方法开始执行
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        long time = end - begin;
        //开始记录日志
        recordLog(joinPoint,time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint,long time){
        //获取方法有日志注解的方法名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        log.info("==================开始记录日志=================");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();
        String requestMethod = request.getMethod();
        log.info("===============请求URI=============" + uri);
        log.info("===============请求远程地址=============" + remoteAddr);
        log.info("===============请求方法=============" + requestMethod);
        //获取注解的参数
        log.info("model:{}",annotation.model());
        log.info("operation:{}",annotation.operation());
        log.info("方法执行时间：" + time + "ms");
    }
}
